package ru.braim.weather_app.controllers;

import jakarta.annotation.Nullable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.braim.weather_app.dto.weather.WeatherRequestDTO;
import ru.braim.weather_app.dto.weather.WeatherResponseDTO;
import ru.braim.weather_app.responses.weather.WeatherResponse;
import ru.braim.weather_app.services.CookieService;
import ru.braim.weather_app.services.WeatherService;

@RestController
@RequestMapping("/region/weather")
public class WeatherController {

    private final WeatherService weatherService;
    private final CookieService cookieService;

    public WeatherController(WeatherService weatherService, CookieService cookieService) {
        this.weatherService = weatherService;
        this.cookieService = cookieService;
    }

    @PostMapping("")
    public ResponseEntity<WeatherResponseDTO> createWeather(@RequestBody WeatherRequestDTO weatherRequestDTO,
                                                            @CookieValue("id") @Nullable String cookie) {
        if (!cookieService.checkAuthorizeCookie(cookie)) {
            return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
        }

        WeatherResponse weatherResponse = weatherService.createWeather(weatherRequestDTO);

        return new ResponseEntity<>(weatherResponse.getWeatherResponseDTO(), weatherResponse.getHttpStatus());

    }

    @GetMapping("/{regionId}")
    public ResponseEntity<WeatherResponseDTO> getWeatherById(@PathVariable String regionId,
                                                             @CookieValue("id") @Nullable String cookie) {

        try {

            if (!cookieService.checkAuthorizeCookie(cookie)) {
                return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
            }

            WeatherResponse weatherResponse = weatherService.getWeatherByRegionId(Long.parseLong(regionId));

            return new ResponseEntity<>(weatherResponse.getWeatherResponseDTO(), weatherResponse.getHttpStatus());
        } catch (NumberFormatException exception) {
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }



}
